#!/usr/bin/env python3.8
# -*- encoding: utf-8 -*-
'''
@File    :   crud.py
@Time    :   2023/04/05 10:16:14
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from datetime import date
from sqlalchemy.orm import Session
from . import models, schemas 

# 根据书名查询，支持模糊查询
def get_books_by_name(db: Session, bookname: str):
    return db.query(models.Books).filter(models.Books.bookname.like(f"%{bookname}%")).all()

# 根据书的`ID`删除
def delete_book_by_id(db:Session, bookId:int):
    db_book = db.query(models.Books).filter(models.Books.id == bookId).one_or_none()
    if db_book is None:
        return None
    db.delete(db_book)
    db.commit()
    return True

# 增加书籍信息
def create_book(db:Session, book:schemas.BooksBase):
    curBook = models.Books(
        bookname = book.bookname,
        prices = book.prices,        
    )
    db.add(curBook)
    db.commit()
    db.refresh(curBook)
    return curBook

# 根据书的`ID`修改书籍信息
def update_book_by_id(db:Session, book:schemas.Books):
    db_book = db.query(models.Books).filter(models.Books.id == book.id).one_or_none()
    if db_book is None:
        return None
        
    for var, value in vars(book).items():
        setattr(db_book, var, value) if value else None
    db.commit()
    db.refresh(db_book)
    return db_book